﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AStar.Wrapper;

namespace AStar.Collections
{
    [Serializable]
    public class MyList<T>
    {
        protected ListObj<T> root = null;



        public virtual void Add(T addIt)
        {
            ListObj<T> temp;
            if (root == null)
            {
                root = new ListObj<T>(addIt);
            }
            else
            {
                temp = root;
                while (temp.Next != null)
                {
                    temp = temp.Next;
                }
                temp.Next = new ListObj<T>(addIt);
            }
        }

        public T Get(int i)
        {
            ListObj<T> re1;
            if (i < Count())
            {
                re1 = root;
                for (int j = 0; j < i; j++)
                {
                    re1 = re1.Next;
                }
            }
            else
            {
                throw new IndexOutOfRangeException();
            }
            return re1.Obj;
        }

        public int Count()
        {
            /*if (root.Equals(default(ListObj<T>)))
            {
                return 0;
            }
            else
            {*/
            try
            {
                int size = 0;
                ListObj<T> temp;
                if (root != null)
                {
                    temp = root;
                    size = 1;
                    while (temp.Next != null)
                    {
                        temp = temp.Next;
                        size++;
                    }
                }
                return size;
            }
            catch
            {
                return 0;
            }

        }

        public bool Exists(T obj)
        {
            bool re = false;
            ListObj<T> temp = root;
            while (temp != null)
            {
                if (temp.Obj.Equals(obj))
                {
                    re = true;
                    break;
                }
                temp = temp.Next;
            }
            return re;
        }

        public void Remove(T obj)
        {
            ListObj<T> temp = root;
            if (root.Obj.Equals(obj))
            {
                root = root.Next;
            }
            else
            {
                while (temp.Next != null && !temp.Next.Obj.Equals(obj))
                {
                    temp = temp.Next;
                }
                ListObj<T> temp2 = temp.Next.Next;
                temp.Next = temp2;
            }
        }
    }
}
